import { Controller, Post, Body, HttpCode, HttpStatus, UseGuards, UseInterceptors } from '@nestjs/common';
import { EmailService } from './email.service';
// 导入DTO
import { SendTemplateEmailDto } from './dto/send-email.dto';
// 导入API密钥守卫
import { ApiKeyGuard } from '@/auth/api-key.guard';
import { QuotaInterceptor } from '@/auth/quota-interceptor.interceptor';

@Controller('sms')
export class EmailController {
  constructor(private readonly emailService: EmailService) { }

  /**
   * 发送模板邮件
   */
  @Post('send')
  @HttpCode(HttpStatus.OK)
  @UseGuards(ApiKeyGuard) // 验证 API Key 和签名
  @UseInterceptors(QuotaInterceptor) // 限制调用次数
  async sendTemplate(@Body() dto: SendTemplateEmailDto) {
    // 转换模板参数格式（从DTO的数组格式转为服务所需的Record格式）
    const templateParams = dto.templateParams.reduce((acc, item) => {
      acc[item.Key] = item.Value;
      return acc;
    }, {} as Record<string, string>);

    const result = await this.emailService.sendTemplateEmail(
      dto.to,
      dto.subject,
      templateParams,
      dto.templateId,
    );

    if (result.success) {
      return {
        code: 0,
        message: '模板邮件发送成功',
        data: { messageId: result.messageId },
      };
    } else {
      return {
        code: 1,
        message: result.error || '模板邮件发送失败',
      };
    }
  }
}